package com.ybwh.springboot2.common.meta;

import com.ybwh.springboot2.common.TokenInfo;
import com.ybwh.springboot2.common.annotation.CurrUserId;
import com.ybwh.springboot2.util.TokenUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * controller方法参数解析器
 * </p>
 *
 * @author ybwh
 * @since 2019年5月17日 下午2:30:09
 */
@Slf4j
@AllArgsConstructor
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (UserInfo.class.equals(parameter.getParameterType())) {
            return true;
        }

        if (null != parameter.getParameterAnnotation(CurrUserId.class)) {
            return true;
        }

        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        String token = TokenUtil.getToken(request);
        if (StringUtils.isBlank(token)) {
            log.error("can not get token for  UserInfoArgumentResolver！");
            return null;
        }

        TokenInfo tokenInfo = null;
        if (null == token) {
            return null;
        }

        if (null != parameter.getParameterAnnotation(CurrUserId.class)) {
            return tokenInfo.getUserId();
        } else if (UserInfo.class.equals(parameter.getParameterType())) {
            return null;
        } else {
            log.error("supportsParameter error!");
            return null;
        }

    }

}
